import React, { useEffect, useRef, useState } from 'react'
import style from './style.module.css'
import { Button, Form, Input } from 'antd'
function Socket() {
    const ref = useRef(null)
    const [arr, setArr] = useState([])
    const divRef = useRef()
    const user_id = 'me'
    const [form] = Form.useForm()
    const wsFn = () => {
        ref.current = new WebSocket(`ws://81.70.224.2:8003/koa/ws?user_id=${user_id}&server_id=300`)

        ref.current.onopen = () => {
            console.log('连接成功');
            ref.current.send(JSON.stringify({ "type": "getChatList" }))
        }
        ref.current.onmessage = (e) => {
            const data = JSON.parse(e.data)
            if (data.type === 'getChatList') {
                setArr(data.data)
                setTimeout(() => {
                    divRef.current.scrollTop = 9999
                    form.resetFields()
                }, 1)
            } else if (data.type === 'addMessage') {
                ref.current.send(JSON.stringify({ "type": "getChatList" }))
            } else if (data.type === 'heartbeat') {
                localStorage.setItem('xt', Date.now())
            }
        }
    }
    useEffect(() => {
        wsFn()
    }, [])


    useEffect(() => {
        setInterval(() => {
            ref.current.send(JSON.stringify({ type: "heartbeat" }))
        }, 3000)

        const xin = Date.now()
        const tiao = localStorage.getItem('xt')
        setInterval(() => {
            if (xin - tiao > 5000) {
                console.log('开始重连');
                ref.current.close()
                wsFn()

            }
        }, 10000)

    }, [])
    console.log(arr);
    const onFinish = (value) => {
        if (!value.text) {
            alert('请输入')
            return
        }
        ref.current.send(JSON.stringify({ type: "addMessage", data: { message: value.text, type: 'text' } }))
    }
    return (
        <div className={style.box}>
            <div className={style.main} ref={divRef}>
                {
                    arr.map((item, index) => {
                        return (
                            <div key={index} className={user_id === item.user_id ? style.list1 : style.list2}>
                                <img src={user_id === item.user_id ? item.user_avatar : item.other_avatar} alt="" />
                                <p>{item.message}</p>
                            </div>
                        )
                    })
                }
            </div>
            <div>
                <Form layout="inline" form={form} onFinish={onFinish}>
                    <Form.Item name='text'>
                        <Input style={{ width: 1000 }} />
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType='submit'>发送</Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}

export default Socket
